import React, { Component } from 'react'
import { Form, Input, Button, message } from 'antd'

import './login.less'
import logo from '../../assets/images/logo.png'
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import { reqLogin } from '../../api'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils';
import { Redirect } from 'react-router-dom';

const Item = Form.Item  // 不能写在form之前

// 登录的路由组件
export default class Login extends Component {

  // 对密码进行自定义验证
  validatePwd = (rule, value, callback) => {
    callback() //验证通过
    if (!value) {
      // callback('密码必须输入')
      return Promise.reject(new Error('请输入密码'));
    } else if (value.length < 4) {
      return Promise.reject('密码长度不能小于4位')
    } else if (value.length > 12) {
      return Promise.reject('密码长度不能大于12位')
    } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
      return Promise.reject('密码必须是英文、数字或下划线组成')
    } else {
      return Promise.resolve() //验证通过
    }
  }

  render() {

    // 判断用户是否已经登录，直接跳转到管理页面
    const user = memoryUtils.user
    if(user && user._id) {
      return <Redirect to="/" />
    }

    // methods
    const onFinish = async (values) => {
      const { username, password } = values
      const { data: res } = await reqLogin(username, password)
      if (res.status === 0) {
        message.success('登录成功')
        //保存User
        const user = res.data
        memoryUtils.user = user
        storageUtils.saveUser(user)
        this.props.history.replace('/')
      }
      else
        message.error('登录失败')

    };

    const onFinishFailed = (errorInfo) => {
      message.error('用户名或密码验证失败')
      console.log('Failed:', errorInfo);
    };

    return (
      <div className="login">
        <header className="login-header">
          <img src={logo} alt="logo" />
          <h1>React项目：后台管理系统</h1>
        </header>
        <section className="login-content">
          <h2>用户登录</h2>
          <div>
            <Form
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              className="login-form">
              <Item
                name="username"
                rules={[
                  { required: true, whitespace: true, message: '请输入用户名' },
                  { min: 4, message: '用户名至少4位' },
                  { max: 12, message: '用户名至多12位' },
                  { pattern: !/^[a-zA-Z0-9_]+$/, message: '用户名必须是英文、数字或下划线组成' }
                ]}
              >
                <Input prefix={<UserOutlined style={{ color: "rgba(0,0,0,0.5)" }} />} />
              </Item>
              <Item
                name="password"
                rules={[
                  { validator: this.validatePwd }
                ]}
              >
                <Input.Password prefix={<LockOutlined style={{ color: "rgba(0,0,0,0.5)" }} />} />
              </Item>
              <Item>
                <Button type="primary" htmlType="submit" className="login-form-button">
                  登录
                </Button>
              </Item>
            </Form>
          </div>
        </section>
      </div>
    )
  }
}

// 1.前台表单验证
// 2.收集表单输入数据